#include "EventLoop.h"
#include "Channel.h"
#include <string.h>
#include <unistd.h>
#include <sys/timerfd.h>
#include <thread>
#include <iostream>

using std::thread;

using std::cout;

//test1
void testEventLoopFunc()
{
    cout << "testEventLoopFunc()>>pid=" << getpid() << " tid=" << CurrentThread::tid() << "\n";
    EventLoop loop;
    loop.loop();
}

int oneLoopPerThread()
{
    cout << "main()>>pid=" << getpid() << " tid=" << CurrentThread::tid() << "\n";
    EventLoop loop;
    thread t(testEventLoopFunc);
    
    loop.loop();
    if(t.joinable())
    {
        t.join();
    }
    return 0;
}

//test2
/*EventLoop *g_loop;
void threadFunc()
{
    g_loop->loop();
}
void negaTestEventLoop()
{
    EventLoop loop;
    g_loop = &loop;
    thread t(threadFunc);
    t.join();
}*/

// test3 EventLoop Poller Channel
EventLoop *g_loop;
void timeout()
{
    cout << "TIMEOUT!!\n";
    g_loop->quit();
}

void testQuit()
{
    EventLoop loop;
    g_loop = &loop;
    int timerfd = ::timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
    Channel channel(&loop, timerfd);
    channel.setReadCallback(timeout);
    channel.enableReading();
    struct itimerspec howlong;
    bzero(&howlong, sizeof howlong);
    howlong.it_value.tv_sec = 5;
    ::timerfd_settime(timerfd, 0, &howlong, NULL);
    loop.loop();
    ::close(timerfd);
}


//test4
#include "Acceptor.h"

void testAcceptor()
{
    InetAddress peerAddr("127.0.0.1", 8080);
    EventLoop loop;
    Acceptor acceptor(&loop, peerAddr);
    acceptor.setNewConnectionCallback([](int sockfd, const InetAddress &addr)
    {
        cout << "New connection accepted: sockfd=" << sockfd
             << ", addr=" << addr.ip() << "\n";
        ::close(sockfd); // For testing, we just close the connection immediately
    });
    acceptor.listen();
    loop.loop();
}
int main()
{
    // oneLoopPerThread();
    // negaTestEventLoop();
    // testQuit();
    testAcceptor();
}